package com.snakerflow.app.notice.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.snakerflow.app.notice.entity.Notice;
import com.snakerflow.app.notice.service.NoticeManager;
import com.snakerflow.framework.orm.Page;
import com.snakerflow.framework.orm.PropertyFilter;
import com.snakerflow.framework.security.shiro.ShiroUtils;

@Controller
@RequestMapping(value = "/notice")
public class NoticeController {
	
	@Autowired
	private NoticeManager noticeManager;
	
	/**
	 * 分页查询公告，返回公告列表视图
	 * @param model
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model, Page<Notice> page, HttpServletRequest request) {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.ASC);
		}
		page = noticeManager.findPage(page, filters);
		model.addAttribute("page", page);
		return "notice/noticeList";
	}
	
	/**
	 * 新建公告时，返回公告编辑视图
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String create(Model model) {
		model.addAttribute("notice", new Notice());
		return "notice/noticeEdit";
	}
	
	/**
	 * 编辑用户时，返回用户编辑视图
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") Long id, Model model) {
		model.addAttribute("notice", noticeManager.get(id));
		return "notice/noticeEdit";
	}
	
	/**
	 * 编辑用户时，返回用户查看视图
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "view/{id}", method = RequestMethod.GET)
	public String view(@PathVariable("id") Long id, Model model) {
		model.addAttribute("notice", noticeManager.get(id));
		return "notice/noticeView";
	}
	
	/**
	 * 新增、编辑用户页面的提交处理。保存用户实体，并返回用户列表视图
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(Notice notice) {
		notice.setUser(ShiroUtils.getUser());
		notice.setCreateDate(new Date());
		noticeManager.save(notice);
		return "redirect:/notice";
	}
	
	/**
	 * 编辑用户时，返回用户编辑视图
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable("id") Long id, Model model) {
		noticeManager.delete(id);
		return "redirect:/notice";
	}
}
